<template>
  <div class="supplierForm">
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%">
      <el-form ref="formData" :model="formData" :rules="rules" label-width="140px">
        <el-row :gutter="70">
          <el-col :span="12">
            <el-form-item label="厂家名称：" prop="name">
              <el-input
                v-model="formData.name"
                maxlength="200"
                show-word-limit
                class="show-word-limit"
                placeholder="请输入公司名称"
              />
            </el-form-item>
            <el-form-item label="地区：">
              <el-cascader
                v-model="formData.area"
                :options="areaData"
                :props="props"
                separator="/"
                :class="[areaPlaceholder === '请选择' ? '' : 'cascaderHave']"
                :placeholder="areaPlaceholder"
              />
            </el-form-item>
            <el-form-item label="地址：">
              <el-input
                v-model="formData.address"
                maxlength="500"
                show-word-limit
                class="show-word-limit"
                placeholder="请输入详细地址"
              />
            </el-form-item>
            <el-form-item label="备注：">
              <el-input
                v-model="formData.remark"
                maxlength="1000"
                show-word-limit
                type="textarea"
                :rows="2"
                class="show-word-limit"
                :autosize="{ minRows: 2 }"
                placeholder="请输入备注"
              />
            </el-form-item>
            <!-- <el-form-item label="评估日期：">
              <el-date-picker
                v-model="formData.date"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="评分：">
              <el-input-number
                v-model="formData.assessScore"
                controls-position="right"
                :min="0"
                :max="100"
                :precision="0"
              />
            </el-form-item> -->
            <el-form-item ref="assessForm" label="评审表：" prop="assessForm">
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :data="{
                  typeId: 3,
                  id: type === 'edit' ? $attrs.current.id : null
                }"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="reviewFormUploadSuccess"
                multiple
                :limit="1"
                :file-list="formData.assessForm"
              >
                <el-button size="small">
                  点击上传
                  <i class="el-icon-upload el-icon--right" />
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品/服务：" prop="supplies">
              <el-input
                v-model="formData.supplies"
                maxlength="300"
                show-word-limit
                class="show-word-limit"
                placeholder="请输入产品/服务"
              />
            </el-form-item>
            <el-form-item label="供应类型：" prop="supplyTypeId">
              <el-cascader
                v-model="formData.supplyTypeId"
                :options="supplyTypeOptions"
                @change="supplyTypeChange"
              />
            </el-form-item>
            <el-form-item
              v-for="(item, index) in annexList"
              :key="index"
              :ref="item.prop"
              :label="item.label + '：'"
              :prop="item.prop"
            >
              <supplierFileUpload
                :file-list="formData[item.prop]"
                :file-item="item"
                v-bind="$attrs"
                :type="type"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import supplierFileUpload from './supplierFileUpload'
import supplierFileType from './supplierFileType'
import { getArea } from '@/api/system-management'

export default {
  name: 'SupplierForm',
  components: {
    supplierFileUpload
  },
  inheritAttrs: false,
  data() {
    return {
      dialogVisible: false,
      uploadUrl: process.env.VUE_APP_BASE_API + 'vue/files/upload',
      formData: {
        name: '',
        area: [],
        address: '',
        remark: '',
        date: '',
        assessScore: null,
        supplies: '',
        supplyTypeId: [],
        assessForm: []
      },
      title: '厂家',
      // 附件列表
      annexList: [],
      props: {
        label: 'label',
        value: 'value',
        children: 'cities',
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          getArea({ areaId: node.value }).then((res) => {
            res.data.forEach((el) => {
              el.leaf = level >= 2
            })
            resolve(res.data)
          })
        }
      },
      areaData: [],
      areaPlaceholder: '请选择',
      supplyTypeOptions: [
        {
          value: 2,
          label: '服务',
          children: [
            {
              value: 3,
              label: '校准'
            },
            {
              value: 5,
              label: '能力验证'
            }
          ]
        },
        {
          value: 1,
          label: '供应品',
          children: [
            {
              value: 9,
              label: '设备'
            },
            {
              value: 10,
              label: '耗材'
            },
            {
              value: 11,
              label: '辅助设备'
            },
            {
              value: 12,
              label: '标准物质'
            }
          ]
        }
      ],
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        supplies: [{ required: true, message: '请输入产品/服务', trigger: 'blur' }],
        supplyTypeId: [{ required: true, message: '请选择供应类型', trigger: 'change' }],
        assessForm: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        calibrationCapability: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        CNASCertificate: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        CNASProficiencyTestingProviderCertificate: [
          { type: 'array', required: true, message: '请上传文件', trigger: 'change' }
        ],
        scopeOfProficiencyTesting: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        consumableInspectionReport: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        calibrationBusinessLicense: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        capabilityVerificationBusinessLicense: [
          { type: 'array', required: true, message: '请上传文件', trigger: 'change' }
        ],
        deviceBusinessLicense: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        consumableBusinessLicense: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }]
      },
      type: ''
    }
  },
  mounted() {
    getArea({ areaId: null }).then((res) => {
      this.areaData = res.data
    })
  },
  methods: {
    // 修改供应类型回调函数
    supplyTypeChange(val) {
      switch (val[1]) {
        case 3:
          this.setFormItem(supplierFileType.calibration)
          this.annexList = supplierFileType.calibration
          break
        case 5:
          this.setFormItem(supplierFileType.capabilityVerification)
          this.annexList = supplierFileType.capabilityVerification
          break
        case 9:
          this.setFormItem(supplierFileType.device)
          this.annexList = supplierFileType.device
          break
        case 10:
          this.setFormItem(supplierFileType.consumable)
          this.annexList = supplierFileType.consumable
          break
        case 11:
          this.setFormItem(supplierFileType.accessoryDevice)
          this.annexList = supplierFileType.accessoryDevice
          break
        case 12:
          this.setFormItem(supplierFileType.standardMaterial)
          this.annexList = supplierFileType.standardMaterial
          break
        default:
          this.setFormItem()
          this.annexList = []
          break
      }
    },
    // 删除旧form文件上传项,设置新文件上传项
    setFormItem(formItem) {
      if (this.annexList !== []) {
        for (const item of this.annexList) {
          for (const key in this.formData) {
            if (key === item.prop) {
              delete this.formData[key]
            }
          }
        }
      }
      if (formItem !== []) {
        for (const item of formItem) {
          this.formData[item.prop] = []
        }
      }
    },
    is(type, data) {
      this.dialogVisible = true
      this.type = type
      if (type === 'add') {
        this.title = '新增厂家'
      } else {
        this.title = '编辑厂家'
        this.formData = JSON.parse(JSON.stringify(data))
        this.supplyTypeChange(data.supplyTypeId)
        this.setFormData(JSON.parse(JSON.stringify(data)))
        this.formData.area = [data.provinceId, data.cityId, data.countryId]
        if (data.province !== '') {
          this.areaPlaceholder = data.province + '/' + data.city + '/' + data.country
        }
        // this.formData = data
      }
    },
    setFormData(data) {
      for (const formKey in this.formData) {
        for (const dataKey in data) {
          if (formKey === dataKey) {
            this.formData[formKey] = data[dataKey]
          }
        }
      }
    },
    closeForm() {
      this.dialogVisible = false
      this.$emit('closeForm')
    },
    submitForm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          const obj = JSON.parse(JSON.stringify(this.formData))
          obj['provinceId'] = this.formData.area[0]
          obj['cityId'] = this.formData.area[1]
          obj['countryId'] = this.formData.area[2]
          this.$emit('submitForm', obj, this.type)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleRemove(file, fileList) {
      this.formData.assessForm = []
    },
    handlePreview(file) {
      console.log(file)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    reviewFormUploadSuccess(res, file) {
      this.formData.assessForm.push(res)
      this.$refs.assessForm.clearValidate()
    }
  }
}
</script>

<style lang="less" scoped>
.supplierForm {
  height: 99%;
  /deep/.el-dialog__body {
    padding: 30px 60px;
  }
  /deep/label {
    font-weight: 500;
  }
  /deep/ .el-cascader {
    width: 100%;
  }
  /deep/.el-form-item {
    margin-bottom: 15px;
  }
  /deep/.el-date-editor {
    width: 100%;
  }
  .cascaderHave {
    /deep/.el-input__inner::placeholder {
      color: #606266;
    }
  }
}
</style>
